package org.gdpu.service.impl;

import org.gdpu.base.DaoSupport;
import org.gdpu.model.BloodBank;
import org.gdpu.model.BloodMatch;
import org.gdpu.model.BloodSum;
import org.gdpu.model.BloodType;
import org.gdpu.service.BloodMatchService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: willson
 * Date: 13-11-16
 * Time: 下午8:06
 * To change this template use File | Settings | File Templates.
 */

@Service
@Transactional
public class BloodMatchServiceImpl extends DaoSupport<BloodMatch> implements BloodMatchService {

    @Override
    public List<BloodBank> findBloodBankByBloodVolume(double volume, BloodType bloodType) {

        double sum = 0.0d;
        List<BloodBank> bloodBanks = new ArrayList<BloodBank>();

        if (!IsRich(volume, bloodType))
            return bloodBanks;

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", 1);
        params.put("bloodType", bloodType);
        List<BloodBank> banks = (List<BloodBank>) this.findByFields(BloodBank.class, params);

        for (BloodBank bloodBank : banks) {
            sum += bloodBank.getBloodVolume();
            if ((sum - volume) <= 150.0d)
                bloodBanks.add(bloodBank);
            else {
                break;
            }
        }
        if (sum < volume)
            bloodBanks.clear();
        return bloodBanks;
    }

    private boolean IsRich(double volume, BloodType bloodType) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("bloodType", bloodType.getBloodType());
        BloodSum bloodSum = (BloodSum) this.findSpecialObject(BloodSum.class, params);
        if (bloodSum.getSum() >= volume)
            return true;
        else
            return false;
    }
}
